package controller;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import vo.AjaxResult;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * Author：汤小洋
 * Date：2023-07-06 13:52
 * Description：<描述>
 */
@RestController
public class UploadController {

    @RequestMapping("/upload")
    public AjaxResult upload(String name, @RequestParam CommonsMultipartFile avatar, HttpServletRequest req) throws IOException {
        System.out.println(name);
        System.out.println(avatar);
        System.out.println(avatar.getOriginalFilename()); // 文件名
        System.out.println(avatar.getSize()); // 文件大小
        System.out.println(avatar.getInputStream()); // 文件流

        String filename = IdUtil.simpleUUID() + "." + FileNameUtil.getSuffix(avatar.getOriginalFilename());
        String filePath = req.getServletContext().getRealPath("upload") + File.separator + filename;
        System.out.println(filePath);

        avatar.transferTo(new File(filePath)); // 写入到磁盘

        return AjaxResult.success(filename);
    }
}
